/**
 * @用途 运行时状态管理库的渲染进程入口
 * @author 黄敏
 * @创建时间 2025-06-22 20:29
 **/

import { ref, type UnwrapRef, watch, type WatchOptions } from '@vue/reactivity'
import { nativeTheme } from 'electron'
import { runtimeStateManager } from './runtime-state-manager'
import debounce from 'lodash/debounce'

export const createRuntimeState = <T>(name: string, defaultValue?: T) => {
  const state = ref<T | undefined>(runtimeStateManager.create<T>(name, defaultValue))
  const unwatchs: (() => void)[] = []

  let unwatch = runtimeStateManager.watch<T>(name, newValue => {
    state.value = newValue
  })

  unwatchs.push(unwatch)

  return {
    get state() {
      return state.value as T | undefined
    },

    set: (value: T) => {
      runtimeStateManager.set(name, value)
    },
    destroy: () => {
      unwatchs.forEach(unwatch => unwatch())
      runtimeStateManager.releaseMain(name)
    },
    watch: (
      callback: (newVal: UnwrapRef<T>, oldVal?: UnwrapRef<T>) => void,
      options?: WatchOptions
    ) => {
      const unwatch = watch(state, (newVal, oldVal) => callback(newVal, oldVal), options)
      unwatchs.push(unwatch)
      return unwatch
    }
  }
}

export const systemTheme = (() => {
  const sysTheme = () => (nativeTheme.shouldUseDarkColorsForSystemIntegratedUI ? 'dark' : 'light')

  const systemTheme = createRuntimeState<'light' | 'dark'>('systemTheme', sysTheme())

  const updateSystemTheme = () => {
    systemTheme.set(sysTheme())
  }

  updateSystemTheme()

  const updateSysTheme = debounce(updateSystemTheme, 300)

  // 初始化运行时状态
  // 监听系统主题变化，动态更新 systemTheme
  nativeTheme.on('updated', updateSysTheme)

  return systemTheme
})()
